import React, { useMemo, useRef } from "react";
import { Badge } from "antd";

import {ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { helper } from "@yaf/utils";
import { EnumAuthKey, permission } from "@/service/permission";
import { useThemeToken } from "@/constants";

import { EnumLoginStatusList } from './constants'
import { getDataAction, filterItems } from './proTableDriver';
import { RespDataType } from '../api';
import { getClearLogBtn } from "./btns";


const List: React.FC = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(), []);

  return <ProTable
    ref={proTableRef}
    dataAction={getDataAction(proTableRef)}
    rowKey={"infoId"}
    theme={themeToken.proTableToken}
    headerProps={{
      operatorProps: {
        btnList: [
          { innerType: "delete", authKey: EnumAuthKey.sysLoginLog.removeButton },
          { ExtendComponent: getClearLogBtn(), authKey: EnumAuthKey.sysLoginLog.clearButton }
        ].filter((item) => permission.can(item.authKey)),
      },
      filterProps: {
        maxWidth: "100%",
        filterItems
      }
    }}
    contentProps={{
      tableProps: {
        columns,
      }
    }}
    onError={(msg) => console.error(msg)}
  />
}

export default List;

const getColumns = () => {
  const statusToInfo = helper.convertArrayToObj(EnumLoginStatusList);

  const columns: TableType.ColumnsType<RespDataType.LoginLogItem> = [
    {
      title: '序号',
      dataIndex: 'infoId',
    },
    {
      title: '登录名称',
      dataIndex: 'loginName',
    },
    {
      title: '登录IP地址',
      dataIndex: 'ipaddr',
    },
    {
      title: '登录地点',
      dataIndex: 'loginLocation',
    },
    {
      title: '浏览器',
      dataIndex: 'browser',
    },
    {
      title: '操作系统',
      dataIndex: 'os',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const { label, color } = statusToInfo[value];
        return <Badge color={color} text={label} />
      }
    },
    {
      title: '提示消息',
      dataIndex: 'msg',
    },
    {
      title: '访问时间',
      dataIndex: 'loginTime',
    },
  ];

  return columns;
}
